package com.MediaVaultTest;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class Delete extends HttpServlet {
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException {
		String stringKey = req.getParameter("key");
		Key key = KeyFactory.stringToKey(stringKey);
		//Get the format
	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    Format format = pm.getObjectById(Format.class, key);
	    //delete the file
        blobstoreService.delete(format.getBlobKey());
        //clean up the data structures
        Media media = format.getMedia();
        if(media.getCover()!=null){
        	blobstoreService.delete(media.getCover());
        }
        UserStore userStore = media.getUserStore();
        userStore.setmbStorage(userStore.getmbStorage()-format.getSize());
        String stringMedia = media.getKeyForTrans();
        media.removeFormat(format);
        pm.deletePersistent(format);
        //if thats the last format
        if(media.getNumFormats()==0){
        	userStore.removeMediaFile(media);
        	pm.deletePersistent(media);
        	pm.close();
        	res.sendRedirect("/");
        }
        pm.close();
        res.sendRedirect("/viewInfo.jsp?key="+stringMedia);
    }
}